// request post 请求
const curlPost = (url, param, path = null) => {
    showLoading()
    const root = path ? path : getApp().root
    return new Promise((resolve, reject) => {
        wx.request({
            url: root + url,
            method: 'POST', header: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Source": 'erp3',
                "Auth": wx.getStorageSync('token')
            },
            data: param,
            success: async res => {
                hideLoading()
                if (res.data.warn === '你未登录，请登录' || res.data.warn === 'Auth 已失效，请重新登录' || res.data.code === -1) {
                    wx.removeStorageSync('token')
                    showToast(res.data.warn, 'none')
                    // 跳转登录页
                    wx.redirectTo({
                      url: '/pages/login/index'
                    })
                } else if(res.data.code === 1) {
                    resolve(res.data)
                } else{
                    showToast(res.data.warn, 'none')
                }
            }, fail(err) {
                hideLoading()
                showToast(err.errMsg, 'error')
                reject(err)
            }
        })
    })
}
// request get 请求
const curlGet = (url, param, path = null) => {
    showLoading()
    const root = path ? path : getApp().root
    return new Promise((resolve, reject) => {
        wx.request({
            url: root + url, method: 'GET', header: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Source": 'erp3',
                "Auth": wx.getStorageSync('token')
            },
            data: param, success(res) {
                hideLoading()
                if (res.data.warn === '你未登录，请登录' || res.data.warn === 'Auth 已失效，请重新登录' || res.data.code === -1) {
                  wx.removeStorageSync('token')
                  showToast(res.data.warn, 'none')
                  // 跳转登录页
                  wx.redirectTo({
                    url: '/pages/login/index'
                  })
              } else if(res.data.code === 1) {
                  resolve(res.data)
              } else{
                  showToast(res.data.warn, 'none')
              }
            }, fail(err) {
                hideLoading()
                showToast(err.errMsg, 'error')
                reject(err)
            }
        })
    })
}
// 随机token
const suiji = (length = 15) => {
    var c = "abcdefghijklmnopqrstuvwxyz";
    var x = c.length - 1;
    var str = "";
    for (var i = 1; i <= length; i++) {
        var rand = Math.floor(Math.random() * x);
        str = str + c.substr(rand, 1);
        if (i === 1) { //某些语言变量首字母不能是数字
            c = c + "0123456789";
            x = c.length - 1;
        }
    }
    return 'a' + str;
}

//生成从minNum到maxNum的随机数
const randomNum = (minNum, maxNum) => {
    return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
}

//是不是需要留安全距离的ios
const isIPhoneXRegex = () => {
    let model = wx.getSystemInfoSync().model
    return (/iphone\sx/i.test(model) || (/iphone/i.test(model) && /unknown/.test(model)) || /iphone\s11/i.test(model))
}
// 预览图片
const lookImgHandle = (data, arr = []) => {
    let newArr = []
    if (arr.length === 0) {
        newArr = [data]
    } else {
        let bool = Object.prototype.toString.call(arr[0]) === '[object Object]'
        if (bool) {
            arr.forEach(item => {
                newArr.push(item.url)
            })
        } else {
            newArr = arr
        }
    }
    wx.previewImage({
        current: data, urls: newArr,
    })
}

// 微信定位
const wxGetAddress = () => {
    return new Promise((resolve, reject) => {
        // wx.getLocation({
        //     type: 'gcj02', success: res => {
        //         resolve(res)
        //     }, fail: err => {
        //         reject(err)
        //     }
        // })
    })
}

// loading加载提示
const showLoading = () => {
    return new Promise((resolve, reject) => {
        wx.showLoading({
            title: '加载中...', mask: true, success(res) {
                resolve(res)
            }, fail(err) {
                reject(err)
            }
        })
    })
}

// 关闭loading
const hideLoading = () => {
    return new Promise((resolve) => {
        wx.hideLoading()
        resolve()
    })
}

// 提示信息
const showToast = (title = '请求异常', icon = 'none', duration = 1500) => {
    return new Promise((resolve) => {
        wx.showToast({
            title: title, icon: icon, duration: duration, success: () => {
                setTimeout(() => {
                    resolve()
                }, duration)
            }
        })
    })
}


// 数组列表加一个状态
const addSelected = arr => {
    let arrObj = []
    arr.forEach(item => {
        let obj = {
            name: item, selected: false
        }
        arrObj.push(obj)
    })
    return arrObj
}

//状态全改为false
const toAllFalse = (data) => {
    let arr = [...data]
    arr.forEach(item => {
        item.selected = false
    })
    return arr
}
//补零
const addZero = (data) => {
    if (data * 1 < 10) {
        return '0' + data
    } else {
        return data
    }
}
//数组对象加一个状态
const addArrObjSelected = arr => {
    arr.forEach(item => {
        item.selected = false
    })
    return arr
}
// 防抖
let timer;
const debounce = (fn, interval) => {
    clearTimeout(timer);
    timer = setTimeout(function () {
        fn()
    }, interval);
}


//文件上传 url：上传服务器地址、filePaths：上传文件数组（需包含url字段，代表文件路径、param：formData参数默认为空）
const uploadFile = (url, filePaths, param = {}, path = null) => {
    const root = path ? path : getApp().root
    console.log(root)
    let state = 0
    let uploadNum = filePaths.length; // 上传数组的长度
    return new Promise((resolve, reject) => {
        if (uploadNum > 0) {
            for (let i = 0; i < uploadNum; i++) {
                wx.uploadFile({
                    url: root + url,
                    name: 'file',
                    method: 'POST',
                    filePath: filePaths[i].url,
                    header: {
                        'Content-type': 'multipart/form-data',
                        "Source": 'erp3',
                        "Auth": wx.getStorageSync('token')
                    },
                    formData: param,
                    success: async result => {
                        state++;
                        const res = JSON.parse(result.data);
                        if (state === uploadNum) {
                            if (res.code === 1) {
                                resolve(res);
                            } else {
                                wx.showToast({
                                    title: res.warn, icon: 'none', duration: 1500
                                })
                            }
                        }
                    },
                    fail(error) {
                        wx.showToast({
                            title: error, icon: 'none', duration: 1500
                        })
                        reject(error);
                    },
                })
            }
        } else {
            resolve();
            wx.hideLoading();
        }
    })
}
const downFile = (url, fileName = 'zhongkai') => {
    console.log('******需要下载的文件路径*********：' + url)
    let urlArr = url.split('.')
    let suffix = urlArr[urlArr.length - 1]
    console.log('*************文件格式***********' + suffix)
    wx.showLoading({
        title: '努力下载中~',
    })
    wx.downloadFile({
        url: getApp().root + url, filePath: wx.env.USER_DATA_PATH + `/${fileName}`, success(res) {
            // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
            if (res.statusCode === 200) {
                console.log('*******保存到手机的路径********' + res.filePath)
                if (suffix === 'jpg' || suffix === 'png') {
                    wx.saveImageToPhotosAlbum({
                        filePath: res.filePath, success: () => {
                            wx.hideLoading()
                            wx.showToast({
                                title: '保存成功！',
                            })
                            lookImgHandle(res.filePath)
                        }
                    })
                } else {
                    wx.hideLoading()
                    wx.showToast({
                        title: '下载成功！',
                    })
                    wx.openDocument({
                        filePath: res.filePath, showMenu: true
                    })
                }
            }
        }, fail: err => {
            console.log(err)
            wx.hideLoading()
            wx.showToast({
                title: '文件错误！', icon: 'none', duration: 1500
            })
        }
    })
}

const parseStr = (url) => {
    var queryParts = url.slice(url.indexOf("?") + 1).split('&');
    var params = queryParts.length > 0 ? {} : null;
    queryParts.map(function (item) {
        var a = item.split('=')
        params[a[0]] = a[1]
    })
    return params
}

const arrayToJson = (array) => {
    return JSON.stringify(array)
}

const jsonToArray = (string) => {
    return JSON.parse(string)
}

const urlEncode = (string) => {
    return encodeURIComponent(string)
}

const urlDecode = (string) => {
    return decodeURIComponent(string)
}

const _typeof = (obj) => {
    var s = Object.prototype.toString.call(obj);
    return s.match(/\[object (.*?)]/)[1].toLowerCase()
}

const total = (obj, fileds) => {
    let total = 0
    const array = Object.values(obj)
    const type = _typeof(fileds)
    array.forEach(function (item) {
        switch (type) {
            case 'string':
                total += item[fileds] ? Number(item[fileds]) : 0
                break
            case 'array':
                total += fileds.reduce((result, curValue) => (item[result] * item[curValue]))
                break

        }
    })
    return total
}
const count = (obj) => {
    return Object.keys(obj).length
}

const goto = (e) => {
    let obj = e.currentTarget.dataset
    if (obj.url) {
        wx.navigateTo({
            url: obj.url
        })
    }
}

/**************echart 部分******************/
import * as echarts from '../components/ec-canvas/echarts';

const wxCharts = (echartName, fun) => {
    echartName.init((canvas, width, height, dpr) => {
        // 初始化图表
        let barChart = echarts.init(canvas, null, { //echarts会继承父元素的宽高
            width: width, height: height, devicePixelRatio: dpr // 像素
        });
        barChart.setOption(fun);
        return barChart
    });
}

/**
 * 折线图
 * @param data
 *             xData  X坐标 数据格式 ["2021-01","2021-02","2021-03","2021-04","2021-05","2021-06","2021-07","2021-08","2021-09","2021-10","2021-11","2021-12"]
 *             series Y 坐标 [{"name": "采购金额","type": "line","smooth": 1,"data": ["0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","14509.20"]}]
 *             title 标题 ["采购金额"]
 */
const lineChart = (data) => {
    return {
        legend: {
            data: data.title, top: 10, left: 'center', z: 9
        }, grid: {
            containLabel: true
        }, tooltip: {
            show: true, trigger: 'axis'
        }, xAxis: {
            type: 'category', boundaryGap: false, data: data.xData,
        }, yAxis: {
            x: 'center', type: 'value', splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            }
        }, series: data.series
    }
}

const heartBeat = () => {
    showLoading()
    let token = wx.getStorageSync('token')
    wx.request({
        url: getApp().root + '?cla=loginApp&fun=login', method: 'POST',
        header: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Auth": token,
            'Source': 'erp3',
        },
        data: {},
        success(resp) {
            hideLoading()
            let res = resp.data
            if (res.code === 0) {
                login()
            } else {
                wx.setStorageSync('token', res.data.token)
                getApp().globalData.setData = res.data.setData
            }
        },
        fail(err) {
            hideLoading()
            console.log(err)
        }
    })
}
const login = () => {
    showLoading()
    wx.removeStorageSync('token')
    wx.removeStorageSync('uid')
    if(getApp().controlRoot){
      // 服务商逻辑
      wx.qy.login({
          //第三方应用的suiteid，若第三方小程序绑定多个第三方应用时，建议填上该字段。自建应用不填，且必须去掉
          suiteId: 'wwad3a2330bdc6a021',
          success: function (res) {
              if (res.code) {
                  getuserId(res.code)
              } else {
                  hideLoading()
                  wx.showToast({
                      title: '登录失败！' + res.errMsg, icon: 'none', duration: 3000
                  })
              }
          }
      });
    }else{
      wx.qy.login({
        success: function (res) {
            if (res.code) {
                getuserId(res.code)
            } else {
                hideLoading()
                wx.showToast({
                    title: '登录失败！' + res.errMsg, icon: 'none', duration: 3000
                })
            }
        }
      });
    }
}
const getuserId = (code) => {
  //发起网络请求
  wx.request({
    url: getApp().root + '?cla=loginApp&fun=getuserId',
    method: 'POST',
    header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Source": 'erp3',
    }, data: {
        code: code
    }, success(resp) {
        hideLoading()
        const res = resp.data
        if (res.code === 0) {
            wx.showToast({
                title: res.warn, icon: 'none', duration: 15000
            })
        } else {
          console.log('success')
          wx.setStorageSync('token', res.data.token)
          if (res.data.corpid) wx.setStorageSync('corpid', res.data.corpid)
          if (res.data.session_key) wx.setStorageSync('session_key', res.data.session_key)
          if (res.data.userid) wx.setStorageSync('userid', res.data.userid)
          wx.reLaunch({
              url: '/pages/index/index'
          })
        }
    }, fail(err) {
        hideLoading()
        console.log(err)
    }
  })
}

/**
 * 是否是企业微信
 * @returns {boolean}
 */
const isWxwork = () => {
    try {
        const res = wx.getSystemInfoSync()
        return res.environment && res.environment === 'wxwork'
    } catch (e) {
        return false
    }
}


const formatDate = (arg, formate = 'date') => {
    function format(arg) {
        return arg < 10 ? `0${arg}` : arg
    }

    let date = new Date(arg),
        year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds()

    month = format(month)
    day = format(day)
    hour = format(hour)
    min = format(min)
    sec = format(sec)
    if (formate === 'date') {
        return `${year}-${month}-${day}`
    } else {
        return `${year}-${month}-${day} ${hour}:${min}:${sec}`
    }
}

const initNaN = (array, key) => {
    if (array[key]) {
        if (parseFloat(array[key]) === 0) {
            return '0.0'
        } else {
            return array[key]
        }
    } else {
        return '0.0'
    }
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
const formatDateTime = date => {
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[hour, minute, second].map(formatNumber).join(':')}`
}

/**横岗换斜杠  满足Iphone时间格式 */
function rowTocol(str){
  return str.replace(/-/g, "/")
}

/**获取上个月日期 */
function getPreMonth(date) {
  var arr = date.split('/');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var year2 = year;
  var month2 = parseInt(month) - 1;
  if (month2 == 0) {
      year2 = parseInt(year2) - 1;
      month2 = 12;
  }

  if (month2 < 10) {
      month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2;
  return t2;
}
/**获取下个月日期 */
function getNextMonth(date) {
  var arr = date.split('/');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var year2 = year;
  var month2 = parseInt(month) + 1;
  if (month2 == 13) {
      year2 = parseInt(year2) + 1;
      month2 = 1;
  }

  if (month2 < 10) {
      month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2;
  return t2;
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
/**上传文件 */
function uploadFileCRM(url,file,data={}){
  wx.showLoading({
    title: '上传中...',
  })
  let token = wx.getStorageSync('token');
  return new Promise(function(successCallBack,failCallBack){
    wx.uploadFile({
      url: url,
      filePath: file.url,
      name: 'uploadFile',
      header: {
        'Auth':token,
        'Source':'crm'
      },
      formData:data,
      success(res) {
        wx.hideLoading()
        let result = JSON.parse(res.data);
        if(result.code){
          successCallBack(result.data)
        }else{
          wx.showToast({
            title: result.warn,
            icon:'none'
          })
        }
      
      },
      fail: (res) => {
        wx.hideLoading()
        failCallBack(res)
      },
    });
  })
}
/**
 * 用于判断空，Undefined string Array Object
 * 
 */
function isBlank(str){
 
  if (Object.prototype.toString.call(str) ==='[object Undefined]'){
    //空
    return true
  }else if (Object.prototype.toString.call(str) === '[object String]' || Object.prototype.toString.call(str) === '[object Array]') { //字条串或数组
    return str.length==0?true:false
  }else if (Object.prototype.toString.call(str) === '[object Object]') {
    return JSON.stringify(str)=='{}'?true :false
  }else{
    return true
  }
}

/**
 * 设置返回刷新标志
 */
function setBackFlag(){
  var pages = getCurrentPages();
  var prevPage = pages[pages.length - 2]; //上一个页面
  //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
  prevPage.setData({
    isBack:true,
  })
}

/**格式化日期**/
function formatDateCRM(format='Y/m/d',date='') {
  let dateObj = date?new Date(date):new Date();
  let year = dateObj.getFullYear();
  format = format.replace('Y',year);
  let month = formatNumber(dateObj.getMonth()+1);
  format = format.replace('m',month);
  let day = formatNumber(dateObj.getDate());
  format = format.replace('d',day);
  let hour = formatNumber(dateObj.getHours());
  format = format.replace('H',hour);
  let minute = formatNumber(dateObj.getMinutes());
  format = format.replace('i',minute);
  let second = formatNumber(dateObj.getSeconds());
  format = format.replace('s',second);
  return format;
} 


/**************echart 部分结束******************/

module.exports = {
    curlGet,
    curlPost,
    showLoading,
    hideLoading,
    addSelected,
    addArrObjSelected,
    debounce,
    addZero,
    showToast,
    lookImgHandle,
    uploadFile,
    toAllFalse,
    isIPhoneXRegex,
    suiji,
    wxGetAddress,
    randomNum,
    downFile,
    parseStr,
    arrayToJson,
    jsonToArray,
    urlEncode,
    urlDecode,
    total,
    count,
    goto,
    _typeof,
    wxCharts,
    lineChart,
    heartBeat,
    login,
    initNaN,
    isWxwork,
    formatDate,
    formatTime,
    formatDateTime,
    isBlank,
    getPreMonth,
    getNextMonth,
    rowTocol,
    uploadFileCRM,
    setBackFlag,
    formatDateCRM
}
